// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package progress

import (
	"time"

	"go.uber.org/atomic"
)

type renderer struct {
	isUpdaterRunning atomic.Bool
	stopChan         chan struct{}
	stopFinishedChan chan struct{}
	renderFn         func()
}

func newRenderer() *renderer {
	return &renderer{
		isUpdaterRunning: atomic.Bool{},
		stopChan:         nil,
		stopFinishedChan: nil,
		renderFn:         nil,
	}
}

func (r *renderer) startRenderLoop() {
	if r.renderFn == nil {
		panic("renderFn must be set")
	}
	if !r.isUpdaterRunning.CompareAndSwap(false, true) {
		return
	}
	r.stopChan = make(chan struct{})
	r.stopFinishedChan = make(chan struct{})
	go r.renderLoopFn()
}

func (r *renderer) stopRenderLoop() {
	if !r.isUpdaterRunning.CompareAndSwap(true, false) {
		return
	}
	r.stopChan <- struct{}{}
	close(r.stopChan)
	r.stopChan = nil

	<-r.stopFinishedChan
	close(r.stopFinishedChan)
	r.stopFinishedChan = nil
}

func (r *renderer) renderLoopFn() {
	ticker := time.NewTicker(refreshRate)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			r.renderFn()
		case <-r.stopChan:
			r.renderFn()
			r.stopFinishedChan <- struct{}{}
			return
		}
	}
}
